Imports System.IO

Public Class Form1

    Private Const ConfirmationMessage As String = "You are about to delete {0} rows. This operation cannot be undone. Do you wish to continue?"

    Private Const EMPTY As String = ""
    Private Const BLANK_CODE As String = " "

    Private Const DISK_NAME_MESSAGE As String = "Disk name must be specified"

    Private Const SPLITTER_SPACE As String = " "
    Private Const SPLITTER_DASH As String = " - "
    Private Const SPLITTER_UNDERSCORE As String = " _ "
    Private Const SINGLE_QUOTE As String = "'"
    Private Const APOSTROPHE As String = "`"

    Private Const IMAGE_EXTENSION As String = ".jpg"

    Private Const CODE_FILTER As String = "code = '{0}'"
    Private Const FILENAME_FILTER As String = "filename LIKE '*{0}*'"
    Private Const VENDOR_FILTER As String = "provider = '{0}'"
    Private Const FILTER_CONCAT As String = " AND "
    Private Const COMMENTS_FILTER As String = "comments LIKE'*{0}*'"
    Private Const LICENSE_FILTER As String = "license = {0}"

    Private Const CODE_CELL As Integer = 0
    Private Const URL_CELL As Integer = 4
    Private Const FILE_ID_CELL As Integer = 5
    Private Const LOCAL_IMAGE_CELL As Integer = 6
    Private Const IMAGE_NAME_CELL As Integer = 7

    Private Const ConnectedStatus As String = "Online..."
    Private Const DisconnectedStatus As String = "Offline..."

    Private Const NumberFilesMessage As String = "Number of Files: {0}"
    Private Const VersionMessage As String = "Version: {0}"

    Private Const Period As String = "."

    Private _splash As UpgradeSlash

    Private _foundProductsList As Hashtable

    Private Sub LoadProvideTotals()

        Me.TotalsTableAdapter.FillByTotalProducts(Me.ProviderTotalData.Totals)

    End Sub

    Private Sub LoadTotalCosts()

        Me.TotalsTableAdapter.Fill(Me.TotalData.Totals)

    End Sub

    Private Sub LoadVendors()

        Me.ProviderTableAdapter.Fill(Me.Providers.Provider)

    End Sub

    Private Sub LoadArtists()

        Me.VendorTableAdapter.Fill(Me.VendorData.Vendor)

    End Sub

    Private Sub LoadNumberFiles()

        ToolStripNumberRecordsLabel.Text = String.Format(NumberFilesMessage, FilesTableAdapter.FileCount)

    End Sub

    Private Sub CheckForUpdate()

        Const NewVersionAvaialble As String = "A new version is available. Would you like to go to the download page?"
        Const UpToDate As String = "There is no new version available"

        Try
            If VersionUpdater.NewVersionAvailable Then
                Dim result As MsgBoxResult = MsgBox(NewVersionAvaialble, _
                                                    MsgBoxStyle.YesNo, _
                                                    "New Version")

                If result = MsgBoxResult.Yes Then
                    System.Diagnostics.Process.Start(My.Settings.DownloadUrl)
                End If
            Else
                MsgBox(UpToDate)
            End If
        Catch ex As VersionException
            MsgBox(ex.Message)
        Catch ex As Exception
            'do nothing
        End Try

    End Sub

    Private Sub CheckConnectionStatus()

        Dim connected As Boolean = False

        connected = Connection.IsConnected

        WorkOfflineToolStripMenuItem.Checked = Not connected
        ConnectionChanged(connected)

    End Sub

    Private Sub ConnectionChanged(ByVal online As Boolean)

        If online Then
            ToolStripConnectionStatusLabel.Text = ConnectedStatus
            ToolStripConnectionStatusLabel.ForeColor = Color.Green
        Else
            ToolStripConnectionStatusLabel.Text = DisconnectedStatus
            ToolStripConnectionStatusLabel.ForeColor = Color.Red
        End If
        ImageViewer.Visible = (Not online)
        ProductPage.Visible = online

    End Sub

    Protected Sub ItemDownloaded(ByVal ItemId As Integer)

        ItemIdLabel.Text = ItemId.ToString
        Application.DoEvents()

    End Sub

    Protected Sub LinkFileMessage(ByVal message As String)

        LinkFileMessages.Text = ControlChars.CrLf & LinkFileMessages.Text
        LinkFileMessages.Text = message & LinkFileMessages.Text
        Application.DoEvents()

    End Sub


    Private Sub LoadFolders(ByVal parentNode As TreeNode)

        Try
            Dim directory As DirectoryInfo = New DirectoryInfo(parentNode.FullPath)
            Dim node As TreeNode

            If parentNode.Nodes.Count = 0 Then

                For Each subDirectory As DirectoryInfo In directory.GetDirectories

                    node = New TreeNode
                    node.Text = subDirectory.Name
                    node.Name = subDirectory.Name
                    node.ImageIndex = 2
                    node.SelectedImageIndex = 1

                    parentNode.Nodes.Add(node)

                Next

            End If

            LoadFiles(directory)

        Catch ex As IOException
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub LoadFiles(ByVal directory As DirectoryInfo)

        FileList.Items.Clear()

        For Each file As FileInfo In directory.GetFiles

            FileList.Items.Add(file.Name)

        Next

    End Sub

    Private Sub LoadDrives()

        DriveView.Nodes.Clear()
        FileList.Items.Clear()

        Dim drivelist() As DriveInfo = DriveInfo.GetDrives
        Dim node As TreeNode

        For Each drive As DriveInfo In drivelist

            node = New TreeNode
            node.Text = drive.Name
            node.Name = drive.Name

            Select Case drive.DriveType

                Case DriveType.CDRom
                    node.ImageIndex = 3
                Case DriveType.Fixed
                    node.ImageIndex = 0
                Case DriveType.Removable
                    node.ImageIndex = 4
            End Select

            DriveView.Nodes.Add(node)

        Next

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        _splash = New UpgradeSlash
        _splash.Show()
        Application.DoEvents()

        Try

            _splash.ChangeMessage("Upgrade Beginning")
            'perform the upgrade
            If VersionUpdater.Upgrade() Then
                _splash.ChangeMessage("Upgrade Successful")
            Else
                _splash.ChangeMessage("Upgrade failed")
                MsgBox("Upgrade failed. A log noting the failures has been made.")
            End If

            _splash.ChangeMessage("Loading file data.")

            Me.LicenseTableAdapter.Fill(Me.LicenseData.License)

            Me.ProductTypeTableAdapter.Fill(Me.ProductTypeData.ProductType)
            Me.FilesTableAdapter.Fill(Me.Products.Files)
            Me.FiguresTableAdapter.Fill(Me.FiguresData.Figures)

            Me.FilesTableAdapter.Fill(Me.Products.Files)
            LoadVendors()
            LoadDrives()
            LoadArtists()
            LoadTotalCosts()
            LoadProvideTotals()

            CheckConnectionStatus()

            LoadNumberFiles()

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub DriveView_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles DriveView.AfterSelect

        Dim selected As TreeNode = e.Node

        LoadFolders(selected)
        selected.Expand()

    End Sub

    Private Function GetSplitterType() As FileLoader.SplitterType

        Dim splitter As FileLoader.SplitterType = FileLoader.SplitterType.Dash

        If SplitterSpace.Checked Then
            splitter = FileLoader.SplitterType.Space
        End If
        If SplitterSecondSpace.Checked Then
            splitter = FileLoader.SplitterType.SecondSpace
        End If
        If SplitterUnderscore.Checked Then
            splitter = FileLoader.SplitterType.Underscore
        End If
        If SplitterSecondUnderscore.Checked Then
            splitter = FileLoader.SplitterType.SecondUnderscore
        End If
        If SplitterUnderscoreNoSpaces.Checked Then
            splitter = FileLoader.SplitterType.UnderscoreNoSpaces
        End If
        If SplitterSecondUnderscoreNoSpaces.Checked Then
            splitter = FileLoader.SplitterType.SecondUnderscoreNoSpaces
        End If
        If SplitterSecondDash.Checked Then
            splitter = FileLoader.SplitterType.SecondDash
        End If
        If SplitterUserSpecified.Checked Then
            splitter = FileLoader.SplitterType.UserDefined
        End If

        Return splitter

    End Function

    Private Sub LoadFiles(ByVal directoryToLoad As DirectoryInfo, _
                          ByVal filenames As Collections.ObjectModel.Collection(Of String))

        For Each file As FileInfo In directoryToLoad.GetFiles

            filenames.Add(file.Name)

        Next

    End Sub

    Private Sub LoadSubDirectories(ByVal directoryToLoad As DirectoryInfo, _
                                   ByVal filenames As Collections.ObjectModel.Collection(Of String))

        LoadFiles(directoryToLoad, _
                  filenames)

        For Each dir As DirectoryInfo In directoryToLoad.GetDirectories

            LoadSubDirectories(dir, _
                               filenames)

        Next

    End Sub

    Private Sub LoadFilesToDatabase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadFilesToDatabase.Click


        Dim providerName As String = Provider.SelectedValue.ToString
        Dim dName As String = DiskName.Text.Trim
        Dim fullFileName As String = ""
        Dim code As String = ""
        Dim fileName As String = ""

        Dim splitter As FileLoader.SplitterType = FileLoader.SplitterType.Dash
        Dim location As FileLoader.SplitterLocation = FileLoader.SplitterLocation.StartOfFileName

        Dim filenames As New Collections.ObjectModel.Collection(Of String)

        If dName.Length = 0 Then
            MsgBox(DISK_NAME_MESSAGE)
            DiskName.Focus()
            Exit Sub
        End If

        Me.Cursor = Cursors.WaitCursor
        Application.DoEvents()

        Try
            Dim directory As DirectoryInfo = New DirectoryInfo(DriveView.SelectedNode.FullPath)

            If SplitterEnd.Checked Then
                location = FileLoader.SplitterLocation.EndOfFileName
            End If
            If SplitterNone.Checked Then
                location = FileLoader.SplitterLocation.None
            End If

            splitter = GetSplitterType()

            If LoadAll.Checked Then

                LoadFiles(directory, _
                          filenames)

            ElseIf LoadAllPlusSubDirectories.Checked Then

                LoadSubDirectories(directory, _
                                   filenames)

            Else

                For Each selectedFile As Object In FileList.SelectedItems

                    fullFileName = CType(selectedFile, String)
                    filenames.Add(fullFileName)

                Next

            End If

            Dim fl As New FileLoader
            If location = FileLoader.SplitterLocation.None Then
                fl.LoadFiles(filenames, _
                             providerName, _
                             dName, _
                             directory.FullName)
            ElseIf splitter = FileLoader.SplitterType.UserDefined Then
                fl.LoadFiles(filenames, _
                             providerName, _
                             dName, _
                             UserSpecifiedSplitter.Text, _
                             location, _
                             NoDuplicates.Checked, _
                             directory.FullName)
            Else
                fl.LoadFiles(filenames, _
                             providerName, _
                             dName, _
                             splitter, _
                             location, _
                             NoDuplicates.Checked, _
                             directory.FullName)
            End If

            Me.FilesTableAdapter.Fill(Me.Products.Files)
            ResultsGrid.Refresh()
            LoadNumberFiles()
            LoadProvideTotals()

        Catch ex As OleDb.OleDbException
            MsgBox(ex.Message)
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub RefreshDiskItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshDiskItem.Click

        LoadDrives()

    End Sub

    Private Sub DownloadImages_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DownloadImages.Click

        Try
            Cursor = Cursors.WaitCursor

            Dim siteToDownlaod As DownloaderFactory.Site

            If SiteDaz3D.Checked Then
                siteToDownlaod = DownloaderFactory.Site.Daz3D
            ElseIf SitePoserPros.Checked Then
                siteToDownlaod = DownloaderFactory.Site.PoserPros
            ElseIf SiteRDNA.Checked Then
                siteToDownlaod = DownloaderFactory.Site.RuntimeDNA
            ElseIf SiteRenderosity.Checked Then
                siteToDownlaod = DownloaderFactory.Site.Renderosity
            End If

            Dim downloader As BaseDownloader = DownloaderFactory.GetDownloader(siteToDownlaod, _
                                                                                My.Settings.ImageDirectory, _
                                                                                ImageViewer)

            AddHandler downloader.DownloadingItem, AddressOf ItemDownloaded

            downloader.Download()

        Catch ex As Exception

        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub


    Private Sub ResultsGrid_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ResultsGrid.DoubleClick

        Dim selectedRow As DataGridViewRow = ResultsGrid.CurrentRow
        Dim fileId As Integer = CType(selectedRow.Cells(FILE_ID_CELL).Value, Integer)
        Dim editForm As New EditFileDetails(fileId)
        editForm.ShowDialog()

    End Sub

    Private Sub ResultsGrid_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ResultsGrid.KeyDown

        If e.KeyCode = Keys.Delete Then
            e.SuppressKeyPress = True
        End If

    End Sub


    Private Sub ResulstGrid_RowEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles ResultsGrid.RowEnter
        If e.RowIndex > -1 Then
            If Not WorkOfflineToolStripMenuItem.Checked Then
                Dim url As String = ResultsGrid.Rows(e.RowIndex).Cells(URL_CELL).Value.ToString
                'ProductPage.Url = New System.Uri(url)
                ProductPage.Navigate(url)
            Else
                ImageViewer.Image = Nothing
                Dim localImage As Boolean = CType(ResultsGrid.Rows(e.RowIndex).Cells(LOCAL_IMAGE_CELL).Value, Boolean)
                If localImage Then
                    Dim image As String = ResultsGrid.Rows(e.RowIndex).Cells(IMAGE_NAME_CELL).Value.ToString
                    If image.Trim.Length > 0 Then
                        image = My.Settings.ImageDirectory & image

                        Dim file As New FileInfo(image)
                        If file.Exists Then
                            ImageViewer.ImageLocation = image
                        End If
                    End If
                End If
            End If
        End If
    End Sub


    Private Sub ApplyFilter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ApplyFilter.Click

        Cursor = Cursors.WaitCursor
        Application.DoEvents()

        Try
            Dim filterExpression As String = EMPTY

            'figure + product type + license + artist + vendor
            If UseFigure.Checked And UseProductType.Checked And UseLicense.Checked And UseArtist.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByFigureAndProductTypeAndLicenseAndArtistAndProvider(Me.Products.Files, _
                                                                                              FigureFilter.SelectedValue.ToString, _
                                                                                              ProductTypeFilter.SelectedValue.ToString, _
                                                                                              CType(LicenseFilter.SelectedValue, Integer), _
                                                                                              ArtistFilter.SelectedValue.ToString, _
                                                                                              VendorFilter.SelectedValue.ToString)

                'figure + product type + license + artist
            ElseIf UseFigure.Checked And UseProductType.Checked And UseLicense.Checked And UseArtist.Checked Then

                Me.FilesTableAdapter.FillByFigureAndProductTypeAndLicenseAndArtist(Me.Products.Files, _
                                                                                   FigureFilter.SelectedValue.ToString, _
                                                                                   ProductTypeFilter.SelectedValue.ToString, _
                                                                                   CType(LicenseFilter.SelectedValue, Integer), _
                                                                                   ArtistFilter.SelectedValue.ToString)

                'figure + product type + license + vendor
            ElseIf UseFigure.Checked And UseProductType.Checked And UseLicense.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByFigureAndProductTypeAndLicenseAndProvider(Me.Products.Files, _
                                                                                     FigureFilter.SelectedValue.ToString, _
                                                                                     ProductTypeFilter.SelectedValue.ToString, _
                                                                                     CType(LicenseFilter.SelectedValue, Integer), _
                                                                                     VendorFilter.SelectedValue.ToString)

                'figure + product type + license
            ElseIf UseFigure.Checked And UseProductType.Checked And UseLicense.Checked Then

                Me.FilesTableAdapter.FillByFigureAndProductTypeAndLicense(Me.Products.Files, _
                                                                          FigureFilter.SelectedValue.ToString, _
                                                                          ProductTypeFilter.SelectedValue.ToString, _
                                                                          CType(LicenseFilter.SelectedValue, Integer))

                'figure + product type + artist + vendor
            ElseIf UseFigure.Checked And UseProductType.Checked And UseArtist.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByFigureAndProductTypeAndArtistAndVendor(Me.Products.Files, _
                                                                                  FigureFilter.SelectedValue.ToString, _
                                                                                  ProductTypeFilter.SelectedValue.ToString, _
                                                                                  ArtistFilter.SelectedValue.ToString, _
                                                                                  VendorFilter.SelectedValue.ToString)

                'figure + product type + artist
            ElseIf UseFigure.Checked And UseProductType.Checked And UseArtist.Checked Then

                Me.FilesTableAdapter.FillByFigureAndProductTypeAndArtist(Me.Products.Files, _
                                                                          FigureFilter.SelectedValue.ToString, _
                                                                          ProductTypeFilter.SelectedValue.ToString, _
                                                                          ArtistFilter.SelectedValue.ToString)

                'figure + license + artist + vendor
            ElseIf UseFigure.Checked And UseLicense.Checked And UseArtist.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByFigureAndLicenseAndArtistAndProvider(Me.Products.Files, _
                                                                                FigureFilter.SelectedValue.ToString, _
                                                                                CType(LicenseFilter.SelectedValue, Integer), _
                                                                                ArtistFilter.SelectedValue.ToString, _
                                                                                VendorFilter.SelectedValue.ToString)

                'figure + license + artist
            ElseIf UseFigure.Checked And UseLicense.Checked And UseArtist.Checked Then

                Me.FilesTableAdapter.FillByFigureAndLicenseAndArtist(Me.Products.Files, _
                                                                     FigureFilter.SelectedValue.ToString, _
                                                                     CType(LicenseFilter.SelectedValue, Integer), _
                                                                     ArtistFilter.SelectedValue.ToString)


                'figure + product type + vendor
            ElseIf UseFigure.Checked And UseProductType.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByFigureAndProductTypeAndProvider(Me.Products.Files, _
                                                                           FigureFilter.SelectedValue.ToString, _
                                                                           ProductTypeFilter.SelectedValue.ToString, _
                                                                           VendorFilter.SelectedValue.ToString)

                'figure + product type
            ElseIf UseFigure.Checked And UseProductType.Checked Then

                Me.FilesTableAdapter.FillByFigureAndProductType(Me.Products.Files, _
                                                                FigureFilter.SelectedValue.ToString, _
                                                                ProductTypeFilter.SelectedValue.ToString)

                'figure + license + vendor
            ElseIf UseFigure.Checked And UseLicense.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByFigureAndLicenseAndProvider(Me.Products.Files, _
                                                                       FigureFilter.SelectedValue.ToString, _
                                                                       CType(LicenseFilter.SelectedValue, Integer), _
                                                                       VendorFilter.SelectedValue.ToString)

                'figure + license
            ElseIf UseFigure.Checked And UseLicense.Checked Then

                Me.FilesTableAdapter.FillByFigureAndLicense(Me.Products.Files, _
                                                                FigureFilter.SelectedValue.ToString, _
                                                                CType(LicenseFilter.SelectedValue, Integer))

                'figure + artist + vendor
            ElseIf UseFigure.Checked And UseArtist.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByFigureAndArtistAndProvider(Me.Products.Files, _
                                                                      FigureFilter.SelectedValue.ToString, _
                                                                      ArtistFilter.SelectedValue.ToString, _
                                                                      VendorFilter.SelectedValue.ToString)

                'figure + artist
            ElseIf UseFigure.Checked And UseArtist.Checked Then

                Me.FilesTableAdapter.FillByFigureAndArtist(Me.Products.Files, _
                                                           FigureFilter.SelectedValue.ToString, _
                                                           ArtistFilter.SelectedValue.ToString)

                'figure + vendor
            ElseIf UseFigure.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByFigureAndProvider(Me.Products.Files, _
                                                             FigureFilter.SelectedValue.ToString, _
                                                             VendorFilter.SelectedValue.ToString)

                'figure
            ElseIf UseFigure.Checked Then

                Me.FilesTableAdapter.FillByFigure(Me.Products.Files, _
                                                  FigureFilter.SelectedValue.ToString)


                'product type + license + artist + vendor
            ElseIf UseProductType.Checked And UseLicense.Checked And UseArtist.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByProductTypeAndLicenseAndArtistAndProvider(Me.Products.Files, _
                                                                                     ProductTypeFilter.SelectedValue.ToString, _
                                                                                     CType(LicenseFilter.SelectedValue, Integer), _
                                                                                     ArtistFilter.SelectedValue.ToString, _
                                                                                     VendorFilter.SelectedValue.ToString)


                'product type + license + artist
            ElseIf UseProductType.Checked And UseLicense.Checked And UseArtist.Checked Then

                Me.FilesTableAdapter.FillByProductTypeAndLicenseAndArtist(Me.Products.Files, _
                                                                          ProductTypeFilter.SelectedValue.ToString, _
                                                                          CType(LicenseFilter.SelectedValue, Integer), _
                                                                          ArtistFilter.SelectedValue.ToString)

                'product type + license + vendor
            ElseIf UseProductType.Checked And UseLicense.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByProductTypeAndLicenseAndProvider(Me.Products.Files, _
                                                                            ProductTypeFilter.SelectedValue.ToString, _
                                                                            CType(LicenseFilter.SelectedValue, Integer), _
                                                                            VendorFilter.SelectedValue.ToString)

                'product type + license
            ElseIf UseProductType.Checked And UseLicense.Checked Then

                Me.FilesTableAdapter.FillByProductTypeAndLicense(Me.Products.Files, _
                                                                 ProductTypeFilter.SelectedValue.ToString, _
                                                                 CType(LicenseFilter.SelectedValue, Integer))

                'product type + artist + vendor
            ElseIf UseProductType.Checked And UseArtist.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByProductTypeAndArtistAndProvider(Me.Products.Files, _
                                                                           ProductTypeFilter.SelectedValue.ToString, _
                                                                           ArtistFilter.SelectedValue.ToString, _
                                                                           VendorFilter.SelectedValue.ToString)

                'product type + artist
            ElseIf UseProductType.Checked And UseArtist.Checked Then

                Me.FilesTableAdapter.FillByProductTypeAndArtist(Me.Products.Files, _
                                                                ProductTypeFilter.SelectedValue.ToString, _
                                                                ArtistFilter.SelectedValue.ToString)

                'product type + vendor
            ElseIf UseProductType.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByProductTypeAndProvider(Me.Products.Files, _
                                                                  ProductTypeFilter.SelectedValue.ToString, _
                                                                  VendorFilter.SelectedValue.ToString)

                'product type
            ElseIf UseProductType.Checked Then

                Me.FilesTableAdapter.FillByProductType(Me.Products.Files, _
                                                       ProductTypeFilter.SelectedValue.ToString)

                'license + artist + vendor
            ElseIf UseLicense.Checked And UseArtist.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByLicenseAndArtistAndProvider(Me.Products.Files, _
                                                                       CType(LicenseFilter.SelectedValue, Integer), _
                                                                       ArtistFilter.SelectedValue.ToString, _
                                                                       VendorFilter.SelectedValue.ToString)

                'license + artist
            ElseIf UseLicense.Checked And UseArtist.Checked Then

                Me.FilesTableAdapter.FillByLicenseAndArtist(Me.Products.Files, _
                                                            CType(LicenseFilter.SelectedValue, Integer), _
                                                            ArtistFilter.SelectedValue.ToString)

                'license + vendor
            ElseIf UseLicense.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByLicenseAndProvider(Me.Products.Files, _
                                                              CType(LicenseFilter.SelectedValue, Integer), _
                                                              VendorFilter.SelectedValue.ToString)

                'license
            ElseIf UseLicense.Checked Then

                Me.FilesTableAdapter.FillByLicense(Me.Products.Files, _
                                                   CType(LicenseFilter.SelectedValue, Integer))

                'artist + vendor
            ElseIf UseArtist.Checked And UseVendor.Checked Then

                Me.FilesTableAdapter.FillByArtistAndProvider(Me.Products.Files, _
                                                             ArtistFilter.SelectedValue.ToString, _
                                                             VendorFilter.SelectedValue.ToString)

                'artist
            ElseIf UseArtist.Checked Then

                Me.FilesTableAdapter.FillByArtist(Me.Products.Files, _
                                                  ArtistFilter.SelectedValue.ToString)

                'vendor
            ElseIf UseVendor.Checked Then

                Me.FilesTableAdapter.FillByProvider(Me.Products.Files, _
                                                    Provider.SelectedValue.ToString)

            Else
                Me.FilesTableAdapter.Fill(Me.Products.Files)
            End If

            If UseCriteria.Checked Then
                If SearchName.Checked Then
                    filterExpression &= String.Format(FILENAME_FILTER, SearchCriteria.Text)
                ElseIf SearchCode.Checked Then
                    filterExpression &= String.Format(CODE_FILTER, SearchCriteria.Text)
                Else
                    filterExpression &= String.Format(COMMENTS_FILTER, SearchCriteria.Text)
                End If
            End If

            ProductsSource.Filter = filterExpression

        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub LinkUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkUpdate.Click

        Try
            Cursor = Cursors.WaitCursor

            Dim lu As New LinkUpdater
            AddHandler lu.UpdaterMessage, AddressOf LinkFileMessage
            If UpdateDaz3D.Checked Then
                lu.UpdateLinks(UpdatePrice.Checked, _
                               ProviderNames.Daz3D)
            End If
            If UpdateRenderosity.Checked Then
                lu.UpdateLinks(UpdatePrice.Checked, _
                               ProviderNames.Renderosity)
            End If
            If UpdatePoserPros.Checked Then
                lu.UpdateLinks(UpdatePrice.Checked, _
                               ProviderNames.PoserPros)
            End If
            If UpdateRuntimeDNA.Checked Then
                lu.UpdateLinks(UpdatePrice.Checked, _
                               ProviderNames.RuntimeDNA)
            End If

            LoadTotalCosts()

            ApplyFilter_Click(sender, _
                              e)

        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub


    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        'this is to only show the option to download data from the provider sites
        'to create the 'update' xml files to certain people to reduce the load
        'on the provider sites
        If My.Settings.JC = 260578 Then
            AdminPanel.Visible = True
        Else
            AdminPanel.Visible = False
        End If

    End Sub

    Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown

        If Not _splash Is Nothing Then
            _splash.Close()
        End If

    End Sub

    Private Sub OpenSearchStartBrowser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenSearchStartBrowser.Click

        SearchStartLocationBrowser.ShowDialog()
        SearchStartLocation.Text = SearchStartLocationBrowser.SelectedPath

    End Sub

    Private Sub Scanning(ByVal path As String)
        ScanMessages.Text = ControlChars.CrLf & ScanMessages.Text
        ScanMessages.Text = path & ScanMessages.Text
        Application.DoEvents()
    End Sub

    Private Sub RuntimeFound(ByVal path As String)
        FoundRuntimesList.Items.Add(path)
        Application.DoEvents()
    End Sub

    Private Sub SearchForRuntimes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchForRuntimes.Click
        Me.Cursor = Cursors.WaitCursor
        Try

            If SearchStartLocation.Text <> "" Then
                Dim report As New RuntimeReport()
                AddHandler report.Scanning, AddressOf Scanning
                AddHandler report.RuntimeFound, AddressOf RuntimeFound
                Dim foundRuntimes As System.Collections.ObjectModel.Collection(Of DirectoryInfo)
                foundRuntimes = report.ScanForRuntimes(SearchStartLocation.Text)
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub SupportThisProjectToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupportThisProjectToolStripMenuItem.Click

        Dim sp As New SupportProject
        sp.ShowDialog()

    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click

        Dim a As New AboutBox
        a.ShowDialog()

    End Sub

    Private Sub WorkOfflineToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WorkOfflineToolStripMenuItem.Click

        If WorkOfflineToolStripMenuItem.Checked Then
            Connection.Disconnect()
        Else
            Connection.Connect()
        End If

        ConnectionChanged(Not WorkOfflineToolStripMenuItem.Checked)

    End Sub

    Private Sub SplitterNone_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SplitterNone.CheckedChanged
        CodeSplitterTypeGroup.Enabled = Not SplitterNone.Checked
    End Sub

    Private Sub SplitterEnd_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SplitterEnd.CheckedChanged
        SplitterSecondDash.Enabled = Not SplitterEnd.Checked
        SplitterSecondSpace.Enabled = Not SplitterEnd.Checked
        SplitterSecondUnderscore.Enabled = Not SplitterEnd.Checked
        SplitterSecondUnderscoreNoSpaces.Enabled = Not SplitterEnd.Checked
    End Sub


    Private Sub PoserDownloadTrackerDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PoserDownloadTrackerDataToolStripMenuItem.Click

        Dim pdtLoader As New PDTImport
        pdtLoader.ShowDialog()

    End Sub

    Private Sub VendorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VendorToolStripMenuItem.Click

        Dim pm As New VendorMaintenance
        AddHandler pm.VendorsChanged, AddressOf LoadVendors
        pm.ShowDialog()

    End Sub

    Private Sub LicenseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LicenseToolStripMenuItem.Click

        Dim lm As New LicenseMaintenance
        lm.ShowDialog()

    End Sub


    Private Sub SendFeatureRequestToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendFeatureRequestToolStripMenuItem.Click

        System.Diagnostics.Process.Start(My.Settings.SupportUrl)

    End Sub

    Private Sub ToolStripVersionCheckLabel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripVersionCheckLabel.Click

        CheckForUpdate()

    End Sub

    Private Sub CheckForNewVersionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckForNewVersionToolStripMenuItem.Click

        CheckForUpdate()

    End Sub

    Private Sub FileRenamerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FileRenamerToolStripMenuItem.Click

        Dim r As New Renamer
        r.ShowDialog()

    End Sub

    Private Sub RefreshGrid()

        Dim e As New EventArgs
        ApplyFilter_Click(Me, _
                          e)

    End Sub

    Private Sub BtachUpdateDeleteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtachUpdateDeleteToolStripMenuItem.Click

        Dim bvu As New BatchVendorUpdate
        AddHandler bvu.BatchUpdate, AddressOf RefreshGrid
        bvu.ShowDialog()

    End Sub

    Private Sub DeleteSelectedRows_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteSelectedRows.Click

        Try
            Dim faAdapter As New FileArtistDataTableAdapters.FileArtistTableAdapter
            Dim irAdapter As New InstalledRuntimesDataTableAdapters.InstalledRuntimesTableAdapter
            Dim fptAdapater As New FileProductTypesDataTableAdapters.FileProductTypeTableAdapter
            Dim ffAdapter As New FileForFigureDataTableAdapters.FileForFigureTableAdapter

            Dim fileId As Integer = -1

            Dim response As DialogResult = MessageBox.Show(String.Format(ConfirmationMessage, ResultsGrid.SelectedRows.Count), _
                                                           "Delete row(s)?", _
                                                               MessageBoxButtons.YesNo, _
                                                               MessageBoxIcon.Question, _
                                                               MessageBoxDefaultButton.Button2)
            If (response = DialogResult.Yes) Then
                For Each row As DataGridViewRow In ResultsGrid.SelectedRows
                    fileId = CType(row.Cells(FILE_ID_CELL).Value, Integer)
                    faAdapter.DeleteAllForFile(fileId)
                    irAdapter.DeleteAllForFile(fileId)
                    fptAdapater.DeleteAllForFile(fileId)
                    ffAdapter.DeleteAllForFile(fileId)
                    ResultsGrid.Rows.Remove(row)
                Next
                ProductsSource.EndEdit()
                FilesTableAdapter.Update(Products.Files)
            End If

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        LoadNumberFiles()

    End Sub

    Private Sub DuplicatesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DuplicatesToolStripMenuItem.Click

        Dim d As New Duplicates
        AddHandler d.DuplicatesUpdated, AddressOf RefreshGrid

        d.ShowDialog()

    End Sub

    Private Sub ProductPage_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles ProductPage.DocumentCompleted

        Try

        Catch ex As Exception
            'supress any errors
        End Try

    End Sub

    Private Sub OpenSearchStartBrowser2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenSearchStartBrowser2.Click

        SearchStartLocationBrowser.ShowDialog()
        InstalledStartLocation.Text = SearchStartLocationBrowser.SelectedPath

    End Sub

    Private Sub ProductFound(ByVal productCode As String)
        FoundProducts.Items.Add(productCode)
        Application.DoEvents()
    End Sub

    Private Sub SearchForInstalledProducts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchForInstalledProducts.Click

        Me.Cursor = Cursors.WaitCursor
        FoundProducts.Items.Clear()
        Try

            If InstalledStartLocation.Text <> "" Then
                Dim installed As New InstalledDaz3DProducts
                AddHandler installed.ProductFound, AddressOf ProductFound
                If UseContentList.Checked Then
                    installed.ScanByContentList(InstalledStartLocation.Text)
                Else
                    installed.Scan(InstalledStartLocation.Text)
                End If
                _foundProductsList = installed.InstalledProducts
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub UpdateInstalledRuntimes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateInstalledRuntimes.Click

        Dim ip As InstalledProduct
        Dim fileIDs As Integer()
        Dim irta As New InstalledRuntimesDataTableAdapters.InstalledRuntimesTableAdapter
        Dim irDS As InstalledRuntimesData
        Dim alreadyAdded As Boolean

        For Each fp As Object In _foundProductsList.Values

            ip = CType(fp, InstalledProduct)

            fileIDs = FileDB.GetFileIDsForProviderProductCode(ProviderNames.Daz3D, _
                                                              ip.ProductCode)

            For Each fileId As Integer In fileIDs
                Try
                    irDS = New InstalledRuntimesData
                    irta.Fill(irDS.InstalledRuntimes, _
                              fileId)
                    alreadyAdded = False
                    For Each irDR As InstalledRuntimesData.InstalledRuntimesRow In irDS.InstalledRuntimes
                        If irDR.runtime.ToLower = ip.Location.ToLower Then
                            alreadyAdded = True
                            Exit For
                        End If
                    Next
                    If Not alreadyAdded Then
                        irta.Insert(fileId, _
                                    ip.Location)
                    End If
                Catch ex As Exception
                    MsgBox(ex.Data)
                End Try
            Next

        Next

    End Sub


    Private Sub ArtistToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ArtistToolStripMenuItem.Click

        Dim am As New ArtistMaintenance
        AddHandler am.ArtistsUpdated, AddressOf LoadArtists
        am.ShowDialog()

    End Sub

    Private Sub Daz3DToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Daz3DToolStripMenuItem.Click

        Dim idh As New ImportDaz3D
        idh.ShowDialog()

    End Sub

End Class
